
import { FormDialog, FormLayout, FormItem, Checkbox } from '@formily/element'
import { createSchemaField } from '@formily/vue'
import { action } from '@formily/reactive'
import { RuFormOwnerTypeApi } from '../../../api/ru-form/ru-form-owner-type'

const ru_form_owner_type_api = new RuFormOwnerTypeApi;
const useProjectFormDataSource = (service) => (field) => {
    field.loading = true
    service(field).then(
        action.bound((data) => {
            field.dataSource = data
            field.loading = false
        })
    )
}

const loadProjectForm = async (field) => {

    const pjfield = field.form.query("project_id").take();
    const pwfield = field.form.query("project_owner_id").take();

    if (pjfield && pwfield) {
        const data = await ru_form_owner_type_api.findFormsByType({ project_id: pjfield.value, project_owner_id: pwfield.value });
        return new Promise((resolve) => {
            resolve(data.data.map(({ id, name, user_type }) => ({ label: name, value: `${id}^${name}^${user_type}` })))
        });
    }
    return new Promise((resolve) => resolve([]));

}


const { SchemaField } = createSchemaField({
    components: {
        FormItem,
        Checkbox,
    },
    scope: {
        useProjectFormDataSource,
        loadProjectForm,
    }
})

// 弹框表单组件
export const OwnerForm = {
    data() {
        const schema = {
            type: 'object',
            properties: {
                ru_form_info: {
                    type: 'array',
                    title: '选择评测表',
                    required: true,
                    'x-decorator': 'FormItem',
                    'x-component': 'Checkbox.Group',
                    'x-component-props': {
                        size: 'small'
                    },
                    'x-reactions': ['{{useProjectFormDataSource(loadProjectForm)}}'],
                },
                project_id: {
                    type: 'string',
                    hidden: true,
                },
                project_owner_id: {
                    type: 'string',
                    hidden: true,
                }

            },
        }
        return {
            schema,
        }
    },
    render(h) {
        return (
            <FormLayout labelCol={4} wrapperCol={14}>
                <SchemaField schema={this.schema} />
                <FormDialog.Footer>
                </FormDialog.Footer>
            </FormLayout>
        )
    },
}